<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item prop="deptId">
<!--        <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="部门"
          style="width: 480px" size="small" /> -->
          <el-select v-model="queryParams.deptId" placeholder="部门" clearable size="small">
            <el-option v-for="item in deptOptions" :key="item.deptId" :label="item.deptName"
              :value="item.deptId" />
          </el-select>
      </el-form-item>

      <el-form-item prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="订单号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item prop="clientId">
          <el-select v-model="queryParams.clientId" placeholder="请选择客户" clearable size="small">
            <el-option v-for="item in clientOptions" :key="item.id" :label="item.name"
              :value="item.id" />
          </el-select>
      </el-form-item> -->
   <!--   <el-form-item prop="lineId">
        <el-select v-model="queryParams.lineId" placeholder="线路" clearable size="small">
          <el-option v-for="item in lineOptions" :key="item.id" :label="item.name"
            :value="item.id" />
        </el-select>
      </el-form-item> -->
      <el-form-item prop="carId">
        <el-select v-model="queryParams.carId" placeholder="车辆" clearable size="small">
          <el-option v-for="item in carOptions" :key="item.id" :label="item.carNumber"
            :value="item.id" />
        </el-select>
      </el-form-item>
 <!--     <el-form-item prop="driverId">
        <el-select v-model="queryParams.driverId" placeholder="驾驶员" clearable size="small">
          <el-option v-for="item in driverOptions" :key="item.id" :label="item.personName"
            :value="item.id" />
        </el-select>
      </el-form-item> -->



      <el-form-item  prop="status">
        <el-select v-model="queryParams.status" placeholder="订单状态" clearable size="small">
          <el-option v-for="dict in dict.type.tms_order_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

    <el-form-item>
        <el-date-picker v-model="daterangeCreateTime" size="small" style="width: 240px" value-format="yyyy-MM-dd"
          type="daterange" range-separator="-" start-placeholder="下单起始日期" end-placeholder="截止日期"></el-date-picker>
        </el-date-picker>
    </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['tms:order:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['tms:order:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['tms:order:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['tms:order:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <dispatch-order :multiple.sync="multiple" :ids.sync="ids"></dispatch-order>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row>
      <el-col :span="3" class="mb10">
        <el-radio-group v-model="queryParams.isStaging" @change="radioChange">
          <el-radio-button v-for="tab in tabs" :label="tab.label" >
            <el-badge :value="tab.badge" class="item">
              {{tab.name}}
            </el-badge>
          </el-radio-button>
        </el-radio-group>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderNo" fixed="left" width="160">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{scope.row.orderNo}}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="部门" prop="deptName" min-width="260"/>
      <el-table-column label="寄件人" prop="sendContacts"  min-width="160"/>
      <el-table-column label="寄件地址" prop="sendAddress"  min-width="260"/>
      <el-table-column label="收件人" prop="takeContacts"  min-width="160"//>
      <el-table-column label="收件地址" prop="takeAddr" min-width="260"/>
      <el-table-column label="是否暂存" align="center" prop="isStaging">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tms_staging_status" :value="scope.row.isStaging" />
        </template>
      </el-table-column>
      <el-table-column label="暂存点" align="center" prop="stagingDeptName"></el-table-column>
      <el-table-column label="状态" align="center" prop="status" fixed="right">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tms_order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" fixed="right">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
            v-hasPermi="['tms:order:query']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['tms:order:edit']" v-if="scope.row.status != '3'">指派</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-truck"  v-if="scope.row.status == '1'"  @click="handleDispatch(scope.row)"
            v-hasPermi="['tms:order:edit']">派车</el-button> -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['tms:order:remove']" v-if="scope.row.status != '3'">作废</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
       <dispatch-select ref="dispatchDraw" title="派车安排" :id.sync="orderId" @updateList="updateList"></dispatch-select>    
  </div>
</template>

<script>
  import {
    listOrder,
    getOrder,
    delOrder,
    addOrder,
    updateOrder,
    initOrderBean
  } from "@/api/tms/order";
  import {treeselect} from '@/api/system/dept'
  import {listClient} from '@/api/tms/client'
  import {listLines} from '@/api/tms/lines'
  import {listCar} from '@/api/tms/car'
  import {listDriver} from '@/api/tms/driver'
  import {listUser} from '@/api/system/user'
  import {listSchedule} from '@/api/tms/schedule'
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import DispatchSelect from "@/components/DispatchSelect";
  export default {
    name: "Order",
    components:{Treeselect,DispatchSelect},
    dicts: ['tms_order_status', 'sys_del_flag', 'tms_order_source_type', 'tms_order_type','tms_staging_status'],
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        sloading:true,
        sdLoading:false,
        // 选中数组
        ids: [],
        clientIds:[],
        radioValue:'0',
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 订单表格数据
        orderList: [],
        deptOptions:[],
        clientOptions:[],
        lineOptions:[],
        carOptions:[],
        driverOptions:[],
        userOptions:[],
        scheduleOptions:[],
        stagingOptions:[],

        //日期区间
        daterangeCreateTime: [],

        items:[],
        // 弹出层标题
        title: "派车",
        orderId:undefined,
        // 是否显示弹出层
        open: false,
        stagingBtn:false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          deptId: undefined,
          orderNo: undefined,
          taskId: undefined,
          objId: undefined,
          fid: undefined,
          entrustNo: undefined,
          orderSerial: undefined,
          sourceType: undefined,
          status: undefined,
          type: undefined,
          signTime: undefined,
          cancelTime: undefined,
          deliveryTime: undefined,
          deliveryType: undefined,
          arriveTime: undefined,
          clientId: undefined,
          clientName: undefined,
          clientContacts: undefined,
          sendAddress: undefined,
          sendContacts: undefined,
          sendDate: undefined,
          sendAddr: undefined,
          takeAddr: undefined,
          takeContacts: undefined,
          takeDate: undefined,
          takeTel: undefined,
          dispatcherId: undefined,
          lineId: undefined,
          lineName: undefined,
          driverId: undefined,
          driverName: undefined,
          driverPhone: undefined,
          carNumber: undefined,
          carId: undefined,
          createBy: undefined,
          createTime: undefined,
          delFlag: undefined,
          isStaging:undefined,
          delFlag:'0',
        },
        querySchedule:{
          pageNum: 1,
          pageSize: 10,
        },
        // 表单参数
        form: {},
        dispatchForm:{
          waybillType:'0'
        },
        stagingForm:{

        },
        // 表单校验
        dispatchRules:{

        },
        rules: {
          deptId: [{
            required: true,
            message: "部门ID不能为空",
            trigger: "blur"
          }],
          orderNo: [{
            required: true,
            message: "订单号不能为空",
            trigger: "blur"
          }],
          taskId: [{
            required: true,
            message: "任务单ID不能为空",
            trigger: "blur"
          }],
          objId: [{
            required: true,
            message: "出入库单ID不能为空",
            trigger: "blur"
          }],
        },

        tabs:[
          {label:undefined,name:'全部',badge:undefined,value:undefined},
          {label:'1',name:'暂存',badge:undefined,value:'1'}
        ],
      };
    },
    created() {
      this.getList();
      this.getDept();
      this.getClient();
      this.getLines();
      this.getCar();
      this.getDriver();
      this.getSchedule();
      this.getUser();
    },
    activated() {
        const time = this.$route.query.t;
        if (time != null && time != this.uniqueId) {
          this.uniqueId = time;
          this.queryParams.pageNum = Number(this.$route.query.pageNum);
          this.getList();
        }
    },
    methods: {
      /** 查询订单列表 */
      getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
          this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0] + '00:00:00';
          this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1] + '23:59:59';
        }
        listOrder(this.queryParams).then(response => {
          this.orderList = response.rows;
          this.total = response.total;
          this.loading = false;

          this.tabs.forEach((item)=>{
          	if(item.label == this.queryParams.isStaging){
          		item.badge = this.total;
          	}else{
          		item.badge = undefined;
          	}
          })
        });
      },
      updateList(){
        this.getList();
      },
      /** 查询部门下来数据 */
      getDept(){
        treeselect().then(response=>{
          this.deptOptions = response.data;
        })
      },
      /** 查询客户列表 */
      getClient(){
        listClient().then(response=>{
          this.clientOptions = response.rows;
        })
      },
      /** 查询线路列表 */
      getLines(){
        listLines().then(response=>{
          this.lineOptions = response.rows;
        })
      },
      /** 查询车辆列表 */
      getCar(){
        listCar().then(response=>{
          this.carOptions = response.rows;
        })
      },
      /** 查询司机列表 */
      getDriver(){
        listDriver().then(response=>{
          this.driverOptions = response.rows;
        })
      },
      /** 查询用户列表 */
      getUser(){
        listUser().then(response=>{
          this.userOptions = response.rows;
        })
      },
      /** 查询车次列表 */
      getSchedule(){
        listSchedule().then(response=>{
          this.scheduleOptions = response.rows;
        })
      },
      radioChange(e){
        this.tabs.forEach(item=>{
            if(item.label == e){
              this.queryParams.isStaging = item.value;
            }
        })
        this.getList();
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          deptId: undefined,
          orderNo: undefined,
          taskId: undefined,
          objId: undefined,
          fid: undefined,
          entrustNo: undefined,
          orderSerial: undefined,
          sourceType: undefined,
          status: "0",
          type: undefined,
          signTime: undefined,
          cancelTime: undefined,
          deliveryTime: undefined,
          deliveryType: undefined,
          arriveTime: undefined,
          memo: undefined,
          clientId: undefined,
          clientName: undefined,
          clientContacts: undefined,
          clientTel: undefined,
          sendAddress: undefined,
          sendContacts: undefined,
          sendDate: undefined,
          sendLat: undefined,
          sendLng: undefined,
          sendAddr: undefined,
          takeAddr: undefined,
          takeContacts: undefined,
          takeDate: undefined,
          takeTel: undefined,
          takeLat: undefined,
          takeLng: undefined,
          takeMemo: undefined,
          dispatcherId: undefined,
          lineId: undefined,
          lineName: undefined,
          driverId: undefined,
          driverName: undefined,
          driverPhone: undefined,
          carNumber: undefined,
          carId: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.clientIds = selection.map(item => item.clientId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        // this.reset();
        // this.open = true;
        // this.title = "添加订单";
        this.$router.push({
          path: '/tms/orderInfo/add',
          query: {
            pageNum: this.queryParams.pageNum
          }
        });
      },
       /** 查看按钮操作 */
      handleDetail(row){
        const id = row.id;
        this.$router.push({
          path: '/tms/orderInfo/detail/' + id,
          query: {
            pageNum: this.queryParams.pageNum
          }
        });
      },
      //  /** 派车按钮操作 */
      // handleDispatch(row){
      //   this.orderId = row.id;
      //   this.$nextTick(()=>{
      //     this.$refs['dispatchDraw'].open();
      //   })
      // },
      /** 重新派车 */
      dispatchCar(){

      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        // this.loading = true;
        // this.reset();
        // const id = row.id || this.ids
        // getOrder(id).then(response => {
        //   this.loading = false;
        //   this.form = response.data;
        //   this.open = true;
        //   this.title = "修改订单";
        // });
       const id = row.id || this.ids;
        this.$router.push({
          path: '/tms/orderInfo/edit/' + id,
          query: {
            pageNum: this.queryParams.pageNum
          }
        });
      },
      handleStaging(){
        this.$router.push({
          path: '/tms/orderInfo/initBean/'+this.ids,
          query: {
            pageNum: this.queryParams.pageNum
          }
        });
      },
      handleStagingSelectionChange(selection){
        this.sdLoading = true;
        let ids = selection.map(item => item.id)
        initOrderBean({orderIds:ids}).then(response=>{
          this.stagingForm.dtls = response.data;
           this.sdLoading = false;
        })
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updateOrder(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addOrder(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除订单编号为"' + ids + '"的数据项？').then(() => {
          this.loading = true;
          return delOrder(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('tms/order/export', {
          ...this.queryParams
        }, `order_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
<style>


</style>
